package cn.gdut.chengcai.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.EmailUtil;
import cn.gdut.chengcai.base.JsonUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.Pager;
import cn.gdut.chengcai.base.PagerUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.entity.EmailTemplateInfo;
import cn.gdut.chengcai.entity.EmailTemplateInfoExample;
import cn.gdut.chengcai.service.EmailTemplateInfoService;
import cn.gdut.chengcai.vo.EmailTemplateInfoVo;

@Controller
@RequestMapping("/admin/template")
public class Admin_TemplateController {

	@Autowired
	protected EmailTemplateInfoService emailTemplateInfoService;

	/**
	 * 邮件模板列表页
	 */
	@RequestMapping("/mail/list")
	public String mailList(HttpSession session, ModelMap map) {
		EmailTemplateInfoExample example = new EmailTemplateInfoExample();
		example.createCriteria().andIsDeletedEqualTo(false);
		List<EmailTemplateInfo> listTotal = emailTemplateInfoService.selectByExample(example);
		Long itemCount = Long.valueOf(String.valueOf(listTotal.size()));
		Pager pager = PagerUtil.getPager(session, itemCount);
		int fromIndex = (pager.getPageNo() - 1) * pager.getPageSize();

		if (fromIndex >= listTotal.size()) {
			fromIndex = 0;
			pager.setPageNo(1);
			session.setAttribute(ConstantUtil.STR_PAGE_NO, "1");
		}
		int toIndex = fromIndex + pager.getPageSize();
		if (toIndex >= listTotal.size()) {
			toIndex = listTotal.size();
		}
		List<EmailTemplateInfo> list = listTotal.subList(fromIndex, toIndex);
		if ((null != list) && (list.size() > 0)) {
			List<EmailTemplateInfoVo> voList = new ArrayList<>();
			try {
				EmailUtil.fillVoList(list, voList);
				map.put("list", voList);
				session.setAttribute("pager", pager);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "/admin/template/mail/list";
	}

	/**
	 * 新增邮件模板页
	 */
	@RequestMapping("/mail/addnew")
	public String mailAddnew(ModelMap map) {
		return "/admin/template/mail/addnew";
	}

	/**
	 * 邮件模板详情页
	 */
	@RequestMapping("/mail/detail/{id}")
	public String mailDetail(ModelMap map, @PathVariable Long id) {

		EmailTemplateInfo entity = emailTemplateInfoService.selectByPrimaryKey(id);
		EmailTemplateInfoVo vo = new EmailTemplateInfoVo();
		try {
			EmailUtil.fillVo(entity, vo);
			map.put("entity", vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/admin/template/mail/detail";
	}

	/**
	 * 修改邮件模板页
	 */
	@RequestMapping("/mail/modify/{id}")
	public String mailModify(ModelMap map, @PathVariable Long id) {

		EmailTemplateInfo entity = emailTemplateInfoService.selectByPrimaryKey(id);
		EmailTemplateInfoVo vo = new EmailTemplateInfoVo();
		try {
			EmailUtil.fillVo(entity, vo);
			map.put("entity", vo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "/admin/template/mail/modify";
	}

	/**
	 * 新增邮件模板操作
	 * 
	 */
	/*
	 * @RequestMapping(value = "/mail/addnewAction", method = {
	 * RequestMethod.POST }, produces = { "application/json;charset=UTF-8" })
	 * 
	 * @ResponseBody public ResponseData<Object> mailAddnewAction(@RequestBody
	 * String jsonString) { ResponseData<Object> result = new ResponseData<>();
	 * result.setIsSuccess(false); try {
	 * 
	 * EmailTemplateInfo entity = (EmailTemplateInfo)
	 * JsonUtil.fromJson(jsonString, EmailTemplateInfo.class);
	 * 
	 * if (entity.getIsDefault() == true) {
	 * emailTemplateInfoService.setNotDefaultByMailType(entity.getType()); }
	 * 
	 * entity.setCreateTime(new Date());
	 * emailTemplateInfoService.insert(entity);
	 * 
	 * result.setIsSuccess(true); } catch (Exception e) {
	 * result.setMessage(MessageUtil.SYSTEM_ERROR); log.error(e.getMessage(),
	 * e); } return result; }
	 */

	/**
	 * 修改邮件模板操作
	 */
	@RequestMapping(value = "/mail/modifyAction", method = { RequestMethod.POST }, produces = {
			"application/json;charset=UTF-8" })
	@ResponseBody
	public ResponseData<Object> mailModifyAction(@RequestBody String jsonString) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			EmailTemplateInfo entity = (EmailTemplateInfo) JsonUtil.fromJson(jsonString, EmailTemplateInfo.class);
			EmailTemplateInfo templateInfo = emailTemplateInfoService.selectByPrimaryKey(entity.getId());
			templateInfo.setType(entity.getType());
			templateInfo.setName(entity.getName());
			templateInfo.setDescribe(entity.getDescribe());
			templateInfo.setIsDefault(entity.getIsDefault());
			templateInfo.setSubject(entity.getSubject());
			templateInfo.setContent(entity.getContent());

			// 同一类型模板只能有一种模板是默认的
			if (entity.getIsDefault() == true) {
				EmailTemplateInfoExample example = new EmailTemplateInfoExample();
				List<EmailTemplateInfo> list = emailTemplateInfoService.selectByExample(example);
				if ((null != list) && (list.size() > 0)) {
					for (EmailTemplateInfo info : list) {
						if(info.getType() == entity.getType()){
							info.setIsDefault(false);
							emailTemplateInfoService.updateByPrimaryKey(info);
						}
						
					}
				}
			}
			emailTemplateInfoService.updateByPrimaryKey(templateInfo);

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

	/**
	 * 删除邮件模板操作
	 */
	@RequestMapping(value = "/mail/delete/{id}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> mailDeleteAction(@PathVariable Long id) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {
			// 逻辑删除
			EmailTemplateInfo entity = emailTemplateInfoService.selectByPrimaryKey(id);
			entity.setIsDeleted(true);
			emailTemplateInfoService.updateByPrimaryKey(entity);
			// emailTemplateInfoService.deleteById(id);
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 新增邮件模板操作
	 * 
	 */

	@RequestMapping(value = "/mail/addnewAction", method = { RequestMethod.POST }, produces = {
			"application/json;charset=UTF-8" })
	@ResponseBody
	public ResponseData<Object> mailAddnewAction(@RequestBody String jsonString) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {
			EmailTemplateInfo entity = (EmailTemplateInfo) JsonUtil.fromJson(jsonString, EmailTemplateInfo.class);

			// 同一类型只能有一种模板是默认的
			if (entity.getIsDefault() == true) {
				EmailTemplateInfoExample example = new EmailTemplateInfoExample();
				List<EmailTemplateInfo> list = emailTemplateInfoService.selectByExample(example);
				if ((null != list) && (list.size() > 0)) {
					for (EmailTemplateInfo info : list) {
						if (info.getType() == entity.getType()) {
							info.setIsDefault(false);
							emailTemplateInfoService.updateByPrimaryKey(info);
						}

					}
				}
			}

			entity.setIsDeleted(false);
			entity.setCreateTime(new Date());
			emailTemplateInfoService.insert(entity);

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

}
